package com.zhkj.txg.module.mine.vm

import android.app.Application
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.base.UploadResponse
import com.zhkj.lib.config.BASE_URL
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.HttpResponseException
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.txg.module.home.entity.HotGoodsResponse
import com.zhkj.txg.module.home.ui.BackTabEvent
import com.zhkj.txg.module.login.model.LoginManager
import com.zhkj.txg.module.mine.entity.*
import com.zhkj.txg.module.mine.model.MineManager
import com.zhkj.txg.module.order.ui.OrderListRefreshEvent
import com.zhkj.txg.utils.ProvinceEntity
import com.zhkj.txg.utils.ProvinceListUtil
import com.zhkj.txg.utils.ProvinceUIData
import com.zhkj.txg.utils.ThirdLoginEvent
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class MineViewModel(application: Application) : BaseViewModel(application) {
    private val mineManager = MineManager()
    private val loginManager = LoginManager()
    private val uploadAvatarLiveData = MutableLiveData<HttpResponse<UploadResponse>>()
    private val weChatResultLiveData = MutableLiveData<ThirdLoginEvent>()
    val userLiveData = MutableLiveData<HttpResponse<UserCenterResponse>>()
    val editUserInfoLiveData = MutableLiveData<HttpResponse<EditUserInfoResponse>>()
    val hotGoodsLiveData = MutableLiveData<HttpResponse<HotGoodsResponse>>()
    val bindWeChatLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    val userBindLiveData = MutableLiveData<HttpResponse<UserBindResponse>>()
    val orderListRefreshLiveData = MutableLiveData<OrderListRefreshEvent>()
    val withdrawListLiveData = MutableLiveData<HttpResponse<WithdrawListResponse>>()
    val referrerLiveData = MutableLiveData<HttpResponse<ReferrerResponse>>()
    val bindInviteLiveData = MutableLiveData<HttpResponse<BaseResponse>>()
    val couponListLiveData = MutableLiveData<HttpResponse<CouponListResponse>>()

    private var numb = 20
    var page = 1
        private set

    // 只有提现日志页需要用到
    var date: String = ""

    // 修改会员资料页面字段
    var provinceList: List<ProvinceEntity>? = null
        private set
    var provinceUIData: ProvinceUIData? = null

    /**
     * 用户信息，只有在编辑用户数据时才会初始化
     */
    var userInfo: UserInfoEntity? = null

    fun getProducts(token: String, restart: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<HotGoodsResponse>(hotGoodsLiveData) {
            override fun onSuccess(resp: HotGoodsResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val hotGoods = mineManager.hotGoods(token, page, numb, listener)
        dispose.add(hotGoods)
    }

    fun userCenter(
        token: String,
        reloadProduct: Boolean = false
    ): MutableLiveData<HttpResponse<UserCenterResponse>> {
        val listener = object : ViewModelSubscribeListener<UserCenterResponse>(userLiveData) {
            override fun onSuccess(resp: UserCenterResponse) {
                super.onSuccess(resp)
                if (reloadProduct) getProducts(token, reloadProduct)
            }

            override fun onFailure(throwable: Throwable) {
                if (throwable is HttpResponseException && throwable.code == 401) RxBus.post(
                    BackTabEvent()
                )
                super.onFailure(throwable)
            }
        }
        val userCenter = mineManager.userCenter(token, listener)
        dispose.add(userCenter)
        return userLiveData
    }

    fun uploadAvatar(
        imageFilePath: String
    ): MutableLiveData<HttpResponse<UploadResponse>> {
        val listener = ViewModelSubscribeListener(uploadAvatarLiveData)
        val uploadPicture = mineManager.uploadPicture(imageFilePath, listener)
        dispose.add(uploadPicture)
        return uploadAvatarLiveData
    }

    fun editUserInfo(token: String, changeAvatarUrl: String, uploadAvatar: Boolean = false) {
        userInfo?.let {
            val listener =
                object : ViewModelSubscribeListener<EditUserInfoResponse>(editUserInfoLiveData) {
                    override fun onSuccess(resp: EditUserInfoResponse) {
                        if (uploadAvatar) resp.userAvatar = BASE_URL + changeAvatarUrl
                        if (resp.userAvatar != AccountManager.getAvatar())
                            AccountManager.saveAvatar(resp.userAvatar ?: "")
                        if (it.nickname != AccountManager.getNickname())
                            AccountManager.saveNickname(it.nickname ?: "")
                        super.onSuccess(resp)
                    }
                }
            val userInfoEdit = mineManager.userInfoEdit(
                token, it.nickname ?: "", it.birthday ?: "",
                when (it.gender) {
                    "男" -> "1"
                    "女" -> "2"
                    else -> "0"
                }, it.province,
                it.city, it.district, changeAvatarUrl, listener
            )
            dispose.add(userInfoEdit)
        }
    }

    /**
     * 获取省市区列表
     */
    fun getProvinceFromAssets() {
        val province = Observable.create(ObservableOnSubscribe<List<ProvinceEntity>> {
            val provinceList = ProvinceListUtil.getProvinceList(getApplication())
            it.onNext(provinceList)
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                provinceList = it
                provinceUIData = ProvinceListUtil.getProvinceUIList(provinceList!!)
            }, { it.printStackTrace() })
        dispose.add(province)
    }

    /**
     * 绑定微信
     */
    fun bindWeChat(code: String) {
        val listener = ViewModelSubscribeListener(bindWeChatLiveData)
        val bindWeChat = mineManager.bindWeChat(AccountManager.getToken(), code, listener)
        dispose.add(bindWeChat)
    }

    /**
     * 微信授权数据观察者
     */
    fun weChatBindSubscribe(): MutableLiveData<ThirdLoginEvent> {
        val subscribe = RxBus.toObservable(ThirdLoginEvent::class.java).observeOn(AndroidSchedulers.mainThread())
            .subscribe({ weChatResultLiveData.value = it }, { it.printStackTrace() })
        dispose.add(subscribe)
        return weChatResultLiveData
    }

    /**
     * 获取用户绑定数据
     */
    fun userBind() {
        val listener = ViewModelSubscribeListener(userBindLiveData)
        val userBind = mineManager.userBind(AccountManager.getToken(), listener)
        dispose.add(userBind)
    }

    /**
     * 订单列表页刷新观察者
     */
    fun orderListStatusSubscribe(): MutableLiveData<OrderListRefreshEvent> {
        val subscribe = RxBus.toObservable(OrderListRefreshEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread()).subscribe({
                orderListRefreshLiveData.value = it
            }, { it.printStackTrace() })
        dispose.add(subscribe)
        return orderListRefreshLiveData
    }

    /**
     * 会员分销日志列表
     */
    fun withdrawList(restart: Boolean) {
        val listener = object : ViewModelSubscribeListener<WithdrawListResponse>(withdrawListLiveData) {
            override fun onSuccess(resp: WithdrawListResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val hotGoods = mineManager.withdrawList(page, numb, date, listener)
        dispose.add(hotGoods)
    }

    /**
     * 会员分销日志列表
     */
    fun memberWithdrawList(restart: Boolean) {
        val listener = object : ViewModelSubscribeListener<WithdrawListResponse>(withdrawListLiveData) {
            override fun onSuccess(resp: WithdrawListResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val hotGoods = mineManager.memberWithdrawList(page, numb, date, listener)
        dispose.add(hotGoods)
    }

    /**
     * 我的邀请人
     */
    fun getReferrer() {
        val referrer = mineManager.getReferrer(ViewModelSubscribeListener(referrerLiveData))
        dispose.add(referrer)
    }

    /**
     * 绑定邀请码
     */
    fun bindInvite(token: String, code: String) {
        val listener = ViewModelSubscribeListener<BaseResponse>(bindInviteLiveData)
        dispose.add(loginManager.bindInvite(token, code, listener))
    }


    fun couponList(restart: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<CouponListResponse>(couponListLiveData) {
            override fun onSuccess(resp: CouponListResponse) {
//                resp.hasMore = resp.data.size >= numb
//                resp.loadMore = page > 1
                super.onSuccess(resp)
//                page += 1
            }
        }
        if (restart) page = 1
        val couponList = mineManager.couponList(
            AccountManager.getToken(), 0, 0, 0,
            page, numb, listener
        )
        dispose.add(couponList)
    }
}